package com.sc.controller;

import com.github.pagehelper.PageInfo;
import com.sc.pojo.*;
import com.sc.service.ExamService;
import com.sc.service.ExamSheetService;
import com.sc.service.TitleAdminService;
import com.sc.service.TitleTypeService;

import com.sc.util.ExcelImportAndDownload;
import com.sc.util.WDWUtil;


import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

@Controller
@RequestMapping("/tac")
public class TitleAdminController {
    @Autowired
    TitleAdminService tas;
    @Autowired
    TitleTypeService tts;
    @Autowired
    ExamService es;
    @Autowired
    ExamSheetService examSheet;
    @RequestMapping("/titleAdmin")
    public String titleAdmin(@RequestParam(defaultValue = "1")Integer pageNum, Map m, HttpSession session,Integer titleSearch){
        System.out.println(titleSearch==null);
        if(titleSearch != null && titleSearch == 0 ) titleSearch = null;
         m.put("titleSearch",titleSearch);
        PageInfo<Title> titlePageInfo = tas.titleAdmin(pageNum, 3,titleSearch);
        List<Titletype> titletypes = tts.showAll();
        session.setAttribute("titletypes",titletypes);
        m.put("p",titlePageInfo);
        return "/exammodol/after/list";
    }

    @RequestMapping("/levelExam")
    public String levelExam(Integer typeId,String difficulty,Map m,HttpSession session){
        List<Title> titles = tas.levelExam(typeId, difficulty);
        System.out.println(titles.size());
        System.out.println(titles);
        if(titles.size() == 0) return "/exammodol/404";
        String type = tts.showOne(typeId).getType();

        Exam exam = new Exam();
//        生成试卷名
        long id = new Date().getTime();
        exam.setId(id);
        StringBuffer admin = new StringBuffer(((User)session.getAttribute("theUser")).getName());
            admin.append(id);
        exam.setName(admin.toString());
        exam.setSubject(type);
        exam.setBegintime(new Date());
        exam.setTimelength(1);
        exam.setAllscore(100.0);
        exam.setChoicenum(titles.size());
        exam.setChoicescore(100.0);
        m.put("exam",exam);
        //添加试卷
        es.addTitleExam(exam);
        m.put("titles",titles);
        //添加考试详情表
        tas.addExamInfo(titles,id);
        return "/exammodol/after/xuanze";
//        return "/exammodol/after/examTitle";
    }


    @RequestMapping(value = "/checkTitle",produces = "text/html;charset=UTF-8")
    @ResponseBody
    public String checkTitle(String title){
        if(tas.checkTitle(title) == null){
            return "题目不存在可以添加";
        }
        return "题目已存在请更换题目";
    }
    //增加题目
    @RequestMapping("/add")
    public String add(Title title){
        tas.add(title);
        return "redirect:/tac/titleAdmin";
    }
    //修改题目
    @RequestMapping("/edit")
    public String edit(Title title){
        tas.edit(title);
        return "redirect:/tac/titleAdmin";
    }

    //删除多个题目
    @RequestMapping("/deleteAll")
    public String deleteAll(Integer[] ids){
        if (ids != null) {
            for (Integer id:ids) {
                //试卷记录表中的对应题目也要删除
                tas.deleteDetail(id);
                //试卷详情表中的题目也要删除
                examSheet.deleteSheet(id);
            }
            tas.deleteAll(ids);
        }
        return "redirect:/tac/titleAdmin";
    }
    //删除单个题目
    @RequestMapping("/delete")
    public String delete(Integer id){
        //试卷记录表中的对应题目也要删除
        tas.deleteDetail(id);
        //试卷详情表中的题目也要删除
        examSheet.deleteSheet(id);
        //题目删除
        tas.delete(id);
        return "redirect:/tac/titleAdmin";
    }
    //去编辑页面
    @RequestMapping("/toEdit")
    public String toEdit(Integer id,Map m){
        Title title = tas.editSelect(id);
        m.put("titleOne",title);
        return "/exammodol/after/edit";
    }


//    批量增加题目
@RequestMapping(value = "/plsc",produces = "text/html;charset=UTF-8")
@ResponseBody
public String toPlsc(MultipartFile file) {
    {
        String msg = "上传成功";
        System.out.println("进来快乐！！！");
        //先判断文件是否为空
        if (file == null) {
            msg = "文件为空!";
            return msg;
        }
        //获取文件名
        String name = file.getOriginalFilename();
        //进一步判断文件是否为空，(判断其大小是否为0或名称是否为null)验证文件名是否合格
        long size = file.getSize();
        if (name == null || "".equals(name) && size == 0 && !WDWUtil.validateExcel(name)) {
            msg = "文件格式不正确";
            return msg;
        }
        //开始读取excel
        Workbook hssfWorkbook = null;
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
            //创建HSSFWorkbook对象
            //创建xssfWorkBook对象
            if (name.endsWith(".xls")) {
                hssfWorkbook = new HSSFWorkbook(inputStream);
            } else if (name.endsWith(".xlsx")) {
                hssfWorkbook = new XSSFWorkbook(inputStream);
            }else {
                return "文件错误类型";
            }

//            HSSFWorkbook hssfWorkbook=new HSSFWorkbook(inputStream);
            //得到一个工作表
            Sheet sheet = hssfWorkbook.getSheetAt(0);
            //先获取表头信息
            org.apache.poi.ss.usermodel.Row rowHead = sheet.getRow(0);
            System.out.println("表头有几列:" + rowHead.getPhysicalNumberOfCells());
            //获取数据的总行数
            int rowNum = sheet.getLastRowNum();
            //要获得的属性

            Integer qkid;     //题目所属科目Id
            String title;      //题目
            String answer;     //题目答案
            String analysis;     //题目解析
            String optiona;      //选项A
            String optionb;      //选项B
            String optionc;       //选项C
            String optiond;      //选项D
            Integer difficult;     //题目难度  1-5 数字越大难度越高
            //先准备集合
            List<Title> list = new ArrayList<Title>();
            //获得所有数据
            for (int i = 1; i <= rowNum; i++) {
                Title question = new Title();
                //获得第i行数据
                Row row = sheet.getRow(i);
                //获得每一列的数据

                org.apache.poi.ss.usermodel.Cell cell = row.getCell((short) 0);
                qkid = (int) cell.getNumericCellValue();
                question.setSid(qkid);

                Cell cell1 = row.getCell((short) 1);
                title = cell1.getStringCellValue().toString();
                question.setTitle(title);

                Cell cell2 = row.getCell((short) 2);
                answer = cell2.getStringCellValue().toString();
                question.setAnswer(answer);

                Cell cell3 = row.getCell((short) 3);
                analysis = cell3.getStringCellValue().toString();
                question.setParse(analysis);

                Cell cell4 = row.getCell((short) 4);
                optiona = cell4.getStringCellValue().toString();
                question.setChoice1(optiona);

                Cell cell5 = row.getCell((short) 5);
                optionb = cell5.getStringCellValue().toString();
                question.setChoice2(optionb);

                Cell cell6 = row.getCell((short) 6);
                optionc = cell6.getStringCellValue().toString();
                question.setChoice3(optionc);

                Cell cell7 = row.getCell((short) 7);
                optiond = cell7.getStringCellValue().toString();
                question.setChoice4(optiond);

                Cell cell8 = row.getCell((short) 8);
                difficult = (int) cell8.getNumericCellValue();
                question.setDifficulty(difficult + "");
                list.add(question);
            }
            //检查对象是否正确
            for (Title question : list) {
                System.out.println(question + "!!!!!!!!!!!!!!!!!!!!!!!");
            }
            System.out.println("==============================================================");
            //将所有对象发往mapper存储
            tas.insertAll(list);
        } catch (IOException e) {
            return "adsd";
        }catch (Exception e){
            return "sdsd";
        }
        finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return msg;
    }
}

    @RequestMapping("/daoChuExcel")
    public void daoChuExcel(Integer[] ids, HttpServletResponse response,HttpSession session){
        if (ids != null) {
            List<Title> titles = tas.selectAllTitle(ids);
            ExcelImportAndDownload.creatResponseWithFileName(response,"题目");
            ExcelImportAndDownload.exportTrackInfoExcel(titles,response,session);
        }
    }

    @RequestMapping("/toAdd")
    public String toAdd(){
        return "/exammodol/after/add";
    }

}
